<!-- 去处理-换车工单 -->
<template>
  <view class="container">
    <FilterNavbar>
      <template #center>
        <view class="navbar-title"> 去处理 </view>
      </template>
    </FilterNavbar>
    <box-info :carId="form.carId" style="margin: 24rpx"></box-info>
    <view class="viewports">
      <ve-card type="none" fold="true">
        <ve-form ref="ve_form" :model="form" :rules="rules">
          <view class="work_tlt">
            <view class="w-l">工单类型：换车工单</view>
            <view class="w-r">换上车信息</view>
          </view>
          <ve-form-item label="车辆来源" class="car-origin">
            <ve-radio v-model="form.carSource" :list="vEnumList" @confirm="radioChange" />
          </ve-form-item>
          <ve-form-item prop="carLicenseNo" required v-if="mode == 'default'" label="车牌号">
            <CustomSelectShortOrder
              v-if="records.orderInfo.orderType == 1"
              @click="customSelectTap"
              tip="请先选择车辆来源后，再选择车牌号"
              :mode="mode"
              :modelValue="form.carLicenseNo"
            />
            <CustomSelectShortOrder
              v-if="records.orderInfo.orderType == 2"
              @click="customSelectTap"
              tip="请先选择车辆来源后，再选择车牌号"
              :mode="mode"
              :modelValue="form.carLicenseNo"
            />
          </ve-form-item>
          <ve-form-item label="排车车型">
            <view>{{ form.carModelName || '-' }}</view>
          </ve-form-item>
          <ve-form-item label="出库里程" unit="公里">
            <ve-input-number :precision="0" :min="0" v-model="form.outCarMileage" />
          </ve-form-item>
          <ve-form-item label="出库油(电)量">
            <ve-input-number :precision="0" :min="1" :max="99999" v-model="form.outCarOil" />
          </ve-form-item>
          <ve-form-item label="备注" labelPosition="top" :borderBottom="false" prop="remark">
            <ve-input type="textarea" v-model="form.remark" placeholder="请输入" :maxlength="100" />
          </ve-form-item>
        </ve-form>
      </ve-card>
    </view>
    <ve-bottom-box>
      <ve-button type="primary" @click="formSubmit" size="long" :loading="okLoading">确认</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script setup lang="ts">
  import { onLoad } from '@dcloudio/uni-app'
  import { ref, nextTick, provide } from 'vue'
  import FilterNavbar from '@/components/FilterNavbar'
  import CustomSelectShortOrder from './shortOrder/components/custom-select.vue'
  import CustomSelectLongOrder from './longOrder/components/custom-select.vue'
  import { goHandleAPI } from '@/api/order/workOrder'
  import boxInfo from './shortOrder/components/box-info.vue'
  import dayjs from 'dayjs'

  import useFormFold from '@/hooks/useFormFold'
  const initFold1 = ref(true)
  const records = ref(null)
  const isChooseCarId = ref(null) //换下车
  const mode = ref('default')
  const vEnumList = ref([
    { value: 1, label: '门店车辆' },
    { value: 3, label: '跨门店调车' },
  ])
  const form = ref({
    carSource: 1,
    carLicenseNo: undefined
  })
  provide('form', form)
  const radioChange = (e) => {
    form.value.carSource = e.value

    form.value.carId = undefined
    form.value.carLicenseNo = undefined
    form.value.carModelId = undefined
    form.value.carModelName = undefined
  }
  const rules = ref({
    carLicenseNo: {
      required: true,
      message: '请选择车牌',
    },
  })

  const _param = (obj) => {
    let str = ''
    if (typeof obj == 'object') {
      for (let i in obj) {
        if (obj[i] == undefined) {
          continue
        }
        str += i + '=' + obj[i] + '&'
      }
    }
    return str.replace(/&$/g, '')
  }
  // 点击车牌选择事件
  const customSelectTap = () => {
    console.log('选车车牌')
    // 跳转选择车牌号页面
    // 换车时间
    let startTime = records.value.orderInfo.replacedCarTime
    const endTime = records.value.orderInfo.endTime
    if (dayjs(startTime).valueOf() > dayjs(endTime).valueOf()) {
      // 将开始时间设置为预计开始时间
      startTime = records.value.orderInfo.startTime
    }
    let orderInfo = {
      // 当前选中的车辆 id
      carId: form.value.carId,
      siteId: records.value.siteId,
      siteName: records.value.siteName,
      modelId: form.value.carModelId,
      modelName: form.value.carModelName,
      startTime: startTime,
      endTime: endTime,
      rentDays: records.value.orderInfo.rentDays,
      carSource: form.value.carSource,
      // 订单来源
      orderSourceName: records.value.orderInfo.orderSourceName,
      orderStatus: records.value.orderInfo.orderStatus,
    }
    // if (props.mode == 'changeCar') {
    //   // 当前选中的车辆 id
    orderInfo.platoonCarId = isChooseCarId.value
    // }
    let paramStr = _param({
      mode: 'select',
      type: records.value.orderInfo.orderType == 1 ? 'short-order' : 'long-order',
      data_json: JSON.stringify({
        ...orderInfo,
        ...platoonModelQueryParam.value,
        carId: form.value.carId,
      }),
      orderInfo_json: JSON.stringify(orderInfo),
    })
    // console.log(orderInfo)
    // return false
    uni.navigateTo({
      url: `/pages/asset/stock/car-stock/selector?${paramStr}`,
    })
  }

  // 选择车牌完成后，函数暴露到上级
  const platoonModelQueryParam = ref({})
  console.log(platoonModelQueryParam.value)

  onLoad((options) => {
    console.log('options', options)
    if (options.record) {
      records.value = JSON.parse(options.record)
      form.value.carSource = records.value.carSource
      form.value.carId = records.value.carId
      form.value.carLicenseNo = records.value.carLicenseNo
      form.value.modelId = records.value.carModelId
      form.value.carModelName = records.value.carModelName
      isChooseCarId.value = records.value.orderInfo.carId //换下车（排车图打开时默认选中

      form.value.id = records.value.id
      form.value.workType = 3
    }
    // 车型选择完成
    uni.$on('carStock:selectCarOk', (carId, option, queryParam) => {
      form.value.carId = carId
      form.value.carLicenseNo = option.licenseNo
      form.value.modelId = option.modelId
      form.value.carModelName = option.modelName
      // 记录弹窗queryParam
      platoonModelQueryParam.value = { ...queryParam }
    })
  })
  const toast = (e) => {
    uni.showToast({
      title: e,
      icon: 'none',
    })
  }
  const ve_form = ref(null)
  const okLoading = ref(false)
  const formSubmit = () => {
    ve_form.value.validate((valid, errors) => {
      console.log(valid)
      if (valid) {
        var res
        var params = {
          ...form.value,
        }
        okLoading.value = true
        goHandleAPI(params)
          .then((res) => {
            okLoading.value = false
            if (res.code == 200) {
              toast(res.message)
              uni.$emit('refreshData')
              uni.navigateBack()
            } else {
              toast(res.message)
              return false
            }
          })
          .catch(() => {
            okLoading.value = false
          })
      } else {
        foldValidate(errors)
        console.log('验证失败', errors)
      }
    })
  }
  defineExpose({})
</script>

<style lang="less" scoped>
  .container {
    background: #f7f8fa;
  }

  .viewports {
    display: flex;
    flex-direction: column;
    padding: 24rpx;
    padding-top: 0;
  }

  .platoon-model {
    width: 100%;
    background: #f7f8fa;
    padding: 34rpx 24rpx;
    font-size: 30rpx;
    color: #191c27;
  }

  .car-origin {
    /deep/ .ve-form-item__body {
      align-items: center;
    }
  }
  .work_tlt {
    height: 100rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid rgba(216, 216, 216, 0.3);
    .w-l {
      font-size: 32rpx;
      font-weight: 600;
      color: #191c27;
    }
    .w-r {
      font-size: 28rpx;
      font-weight: 500;
      color: #ffffff;
      padding: 2rpx 16rpx;
      border-radius: 20rpx;
      background: #3491fa;
      text-align: center;
    }
  }
</style>
